package cn.virens.app.timer;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.app.AppConfig;
import cn.virens.app.cmpt.Component;

public class TimedTaskRegistry implements Component {
	private static final Logger logger = LoggerFactory.getLogger(TimedTaskRegistry.class);

	private final List<TimedTask> tasks = new ArrayList<>();
	private final Timer timer = new Timer();
	private final long delay = 1000;

	/**
	 * 插件 生命周期管理
	 * 
	 * @param  task 定时任务
	 * @return
	 */
	public <T extends TimedTask> T register(T task) {
		return tasks.add(task) ? task : null;
	}

	@Override
	public void initialize(AppConfig config) throws Exception {
		logger.debug("Load TimedTasks...");

		for (TimedTask task : tasks) {
			logger.debug("Load TimedTask {} initialize...", task.name());

			// 初始化 定时任务 & 开启定时
			this.initialize(task, config);
			this.schedule(task);
		}

		logger.debug("Loaded TimedTasks:" + tasks.size());
	}

	@Override
	public void destroy() throws Exception {
		logger.debug("Stop TimedTask...");

		for (TimedTask task : tasks) {
			logger.debug("Stop TimedTask {} stop...", task.name());

			try {
				task.destroy();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}

		// 终止定时器
		timer.cancel();

		logger.debug("Stoped TimedTasks:" + tasks.size());
	}

	/** 初始化定时器 */
	private void initialize(TimedTask task, AppConfig config) {
		try {
			task.initialize(config);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

	/** 启动定时任务 */
	private void schedule(TimedTask task) {
		Integer period = task.period();
		if (period != null && period > 0) {
			timer.schedule(task, delay, period * 1000);
		}
	}
}
